<?php

// 应用公共文件
use Firebase\JWT\JWT;
use think\facade\Request;

//生成验签
function signToken($data) {
    $key = config('adminconfig.JWT_KEY');         //这里是自定义的一个随机字串，应该写在config文件中的，解密时也会用，相当于加密中常用的盐  salt
    $token = array(
        "iss" => $key, //签发者 可以为空
        "aud" => '', //面象的用户，可以为空
        "iat" => time(), //签发时间
        "nbf" => time() + 3, //在什么时候jwt开始生效  （这里表示生成100秒后才生效）
        "exp" => time() + 86400, //token 过期时间
        "data" => $data //记录的userid的信息，这里是自已添加上去的，如果有其它信息，可以再添加数组的键值对
    );
    //  print_r($token);
    $jwt = JWT::encode($token, $key, "HS256");  //根据参数生成了 token
    return $jwt;
}

//验证token
function checkToken($token) {
    $key = config('adminconfig.JWT_KEY');   
    $status = array("code" => 2);
    try {
        JWT::$leeway = 60; //当前时间减去60，把时间留点余地
        $decoded = JWT::decode($token, $key, array('HS256')); //HS256方式，这里要和签发的时候对应
        $arr = (array) $decoded;
        $res['code'] = 1;
        $res['data'] = $arr['data'];
        return $res;
    } catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确
        $status['msg'] = "签名不正确";
        return $status;
    } catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用
        $status['msg'] = "token失效";
        return $status;
    } catch (\Firebase\JWT\ExpiredException $e) { // token过期
        $status['msg'] = "token失效";
        return $status;
    } catch (Exception $e) { //其他错误
        $status['msg'] = "未知错误";
        return $status;
    }
}
//获取客户端ip
function getClientIp() {
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    } elseif ($_SERVER['REMOTE_ADDR'] != '') {
        return $_SERVER['REMOTE_ADDR'];
    } else {
        return $_SERVER['HTTP_CLIENT_IP'];
    }
}

//获取当前格式化时间
function gD(){
    return date('Y-m-d H:i:s');
}

//获取登录者账号信息
function gT(){
    $token = Request::instance()->header('token');
    $res = checkToken($token);
    $object =  json_decode(json_encode($res),true);
    if($object['code']!=1){
        echo  json_encode(['code'=>0,'msg'=>'token失效','data'=>'']);die;
    }  else {
        return $object;
    }
}

//生成随机字符串
function randStr($len){
    $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
    $randStr = str_shuffle($str);//打乱字符串
    return $salt = substr($randStr,0,$len);//substr(string,start,length);返回字符串的一部分
}

 //指定月份的第一天开始和最后一天结束的时间戳
function mFristAndLast($y = "", $m = ""){
    if ($y == "") $y = date("Y");
    if ($m == "") $m = date("m");
    $m = sprintf("%02d", intval($m));
    $y = str_pad(intval($y), 4, "0", STR_PAD_RIGHT);

    $m>12 || $m<1 ? $m=1 : $m=$m;
    $firstday = strtotime($y . $m . "01000000");
    $firstdaystr = date("Y-m-01", $firstday);
    $lastday = strtotime(date('Y-m-d 23:59:59', strtotime("$firstdaystr +1 month -1 day")));

    return array(
        "firstday" => date('Y-m-d',$firstday).' 00:00:00',
        "lastday" => date('Y-m-d',$lastday).' 23:59:59'
    );
}

//计算时间戳
function hours_min($start_time,$end_time,$type)
{
    switch ($type) {

        case 1:
            if(is_string($start_time)){
                if (strtotime($start_time) > strtotime($end_time)) list($start_time, $end_time) = array($end_time, $start_time);
            }

            $sec = $end_time - $start_time;
            $sec = round($sec/60);
            $min = str_pad($sec%60, 2, 0, STR_PAD_LEFT);
            $hours_min = floor($sec/60);
            // $min != 0 && $hours_min .= '.'.$min;
            if($min!=='00'){
                throw new UserException(['msg'=>'给予的时间戳不是完整的开始时间-结束时间', 'code' => '499', 'errorCode'=>'30004']);
            }

            $strArr=[];
            $arr=[];
            $array=[];
            for($i = 0; $i < $hours_min; $i++){
                $b = $start_time + ($i * 3600);
                $e = $start_time + (($i+1) * 3600)-1;
                $strArr[$i][]=date('Y-m-d H:i:s',$b);
                $strArr[$i][]=date('Y-m-d H:i:s',$e);
                $arr[$i][]=$b;
                $arr[$i][]=$e;
                $array[$i]=0;
            }
            return ['hours_min'=>$hours_min,'strArr'=>$strArr,'arr'=>$arr,'array'=>$array];
            break;


        case 2:
            //获取两时间戳内相差几天
            $return=hours_min($start_time,$end_time,$type=1);
            $res=$return['hours_min']/24;
            $rest=(int)$res;
            if($rest-$res!=0){
                throw new UserException(['msg'=>'给予的天时间戳不是完整的开始时间-结束时间', 'code' => '499', 'errorCode'=>'30004']);
            }
            //创建天数数组
            $arr=[];
            $strArr=[];
            $strArr2=[];
            $array=[];
            for($i = 0; $i < $res; $i++){
                $b = $start_time + ($i * 3600 * 24);
                $e = $start_time + (($i+1) * 3600 * 24)-1;
                $arr[$i][]=$b;
                $arr[$i][]=$e;
                $strArr[$i][]=date('Y-m-d H:i:s',$b);
                $strArr[$i][]=date('Y-m-d H:i:s',$e);
                $strArr2[$i]=date('m/d',$e);
                $array[$i]=0;
            }

            return ['res'=>$res,'strArr'=>$strArr,'arr'=>$arr,'array'=>$array,'strArr2'=>$strArr2];

            break;

        case 3:
            //获取两时间戳内相差几周
            $return=hours_min($start_time,$end_time,$type=1);
            $res=$return['hours_min']/(24*7);
            $rest=(int)$res;
            if($rest-$res!=0){
                throw new UserException(['msg'=>'给予的周时间戳不是完整的开始时间-结束时间', 'code' => '499', 'errorCode'=>'30004']);
            }

            //创建周数数组
            $arr=[];
            $strArr=[];
            $array=[];
            for($i = 0; $i < $res; $i++){
                $b = $start_time + ($i * 3600 * (24*7));
                $e = $start_time + (($i+1) * 3600 * (24*7))-1;
                $arr[$i][]=$b;
                $arr[$i][]=$e;
                $strArr[$i][]=date('Y-m-d H:i:s',$b);
                $strArr[$i][]=date('Y-m-d H:i:s',$e);
                $array[$i]=0;
            }


            return ['res'=>$res,'strArr'=>$strArr,'arr'=>$arr,'array'=>$array];
            break;


        case 4:
            //获取两时间戳内相差几月
            $res=getMonthNum(date('Y-m-d',$start_time),date('Y-m-d',$end_time));
            $res=$res+1;
            $arr=dateMonthsSections(date('Y-m',$start_time),date('Y-m',$end_time));

            //创建月数组
            $array=[];
            for ($i=0; $i < $res; $i++) {
                $array[$i]=0;
            }

            return ['res'=>$res,'strArr'=>$arr['strRes'],'arr'=>$arr['res'],'array'=>$array];

            break;


        case 5:
            //获取两时间戳内相差几年
            $res=diffBetweenTwoDate(date('Y-m-d H:i',$start_time),date('Y-m-d H:i',$end_time));
            $res=$res['year'];
            //获取年份数组
            $arr=getTimesRange(date('Y-m-d H:i',$start_time),date('Y-m-d H:i',$end_time));
            $array=[];
            //创建年数组
            for ($i=0; $i < $res; $i++) {
                $array[$i]=0;
            }

            return ['res'=>$res,'strArr'=>$arr['strRes'],'arr'=>$arr['res'],'array'=>$array];
            break;

        case 6;
            if(is_string($start_time)){
                if (strtotime($start_time) > strtotime($end_time)) list($start_time, $end_time) = array($end_time, $start_time);
            }
            $sec = $end_time - $start_time;
            $sec = round($sec/60);
            $min = str_pad($sec%60, 2, 0, STR_PAD_LEFT);
            $hours_min = floor($sec/5);
            // $min != 0 && $hours_min .= '.'.$min;
            if($min!=='00'){
                throw new UserException(['msg'=>'给予的时间戳不是完整的开始时间-结束时间', 'code' => '499', 'errorCode'=>'30004']);
            }

            $strArr=[];
            $arr=[];
            $array=[];
            for($i = 0; $i < $hours_min; $i++){
                $b = $start_time + ($i * 300);
                $e = $start_time + (($i+1) * 300)-1;
                $strArr[$i][]=date('Y-m-d H:i:s',$b);
                $strArr[$i][]=date('Y-m-d H:i:s',$e);
                $arr[$i][]=$b;
                $arr[$i][]=$e;
                $array[$i]=0;
            }
            return ['hours_min'=>$hours_min,'strArr'=>$strArr,'arr'=>$arr,'array'=>$array];
            break;

        default:
            # code...
            break;
    }
}

//将秒 转成时分秒
function gHis($time){
    if ($time/3600 >= 1){
        $H = intval($time/3600);
        $i = intval(($time - $H * 3600) / 60);
        $s = $time - $H * 3600 - $i * 60;
        $info = $H . '时' . $i . '分' . $s .'秒';
    }else{
        if ($time/60 >= 1){
            $i = intval($time / 60);
            $s = $time - $i * 60;
            $info = $i . '分' . $s .'秒';
        }else{
            $info = $time.'秒';
        }
    }
    return $info;
}
